#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();
    this->actOpenFile = new QAction("Open",this);
    this->actOpenFile->setShortcut(QKeySequence::Open);
    this->actOpenFile->setStatusTip(tr("Open a File"));
    connect(actOpenFile,SIGNAL(triggered(bool)),this,SLOT(openFile()));
    ui->menuFile->addAction(this->actOpenFile);

}

void MainWindow::init()
{
    player = new QMediaPlayer(this);
    connect(player,&QMediaPlayer::positionChanged,this,&MainWindow::updatePosition);

    player->setPlaylist(playlist);
    player->setVolume(50);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openFile()
{
    qDebug()<<"打开文件";

    filePath = QFileDialog::getOpenFileName(NULL,"标题",".","*.mp3");
    if (filePath.isEmpty()){
        errorHandling("打开文件错误");
    }
    else{
        qDebug()<<filePath;

    }
    loadMusic();
    return;
}

void MainWindow::loadMusic()
{
    player->setMedia(QUrl::fromLocalFile(filePath));
}
void MainWindow::errorHandling(QString msg){

    QMessageBox::information(NULL,"error",msg);
}

void MainWindow::updatePosition(qint64 position)
{
    ui->playSlider->setMaximum(player->duration() / 1000);
    ui->playSlider->setValue(position / 1000);
}



void MainWindow::on_buttonPlay_clicked()
{
    player->play();
}


void MainWindow::on_playSlider_sliderMoved(int position)
{
    player->setPosition(position * 1000);
}

void MainWindow::on_buttonPause_clicked()
{
    player->pause();
}

void MainWindow::on_buttonStop_clicked()
{
    player->stop();
}
